//
//  WBEmoticonBottomView.swift
//  WeiBo
//
//  Created by 韩菲菲 on 16/8/18.
//  Copyright © 2016年 韩菲菲. All rights reserved.
//

import UIKit

private let tagNumber = 2000

enum  WBEmoticonBottomViewType: Int{
    // 默认
    case Default = 0
    // emoji
    case Emoji = 1
    // 浪小花
    case Lxh = 2
}


class WBEmoticonBottomView: UIStackView {
    
    var closure : ((type:WBEmoticonBottomViewType)->())?
    
    var currentBtn : UIButton?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    // MARK: - 设置UI
    func setupUI() {
        
        backgroundColor = RandomColor()
        
//        //设置填充方向
        axis = .Horizontal
//        
//        //设置填充方式
        distribution = .FillEqually
        
        addChildButton("left", title: "默认" , tag: .Default)
        addChildButton("mid", title: "Emoji", tag: .Emoji)
        addChildButton("right", title: "浪小花", tag: .Lxh)
        
    }
    
    // MARK: - 添加按钮的方法
    func addChildButton(imageName:String , title: String , tag: WBEmoticonBottomViewType) -> UIButton {
        
        let btn = UIButton()
        btn.tag = tag.rawValue + tagNumber
        
        btn.addTarget(self, action: #selector(WBEmoticonBottomView.btnClick(_:)), forControlEvents: .TouchUpInside)
        
        btn.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imageName)_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imageName)_selected"), forState: .Selected)
        
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        
        btn.setTitle(title, forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //默认第一个按钮为选中状态
        if tag == .Default{
        
            btn.selected = true
            
            currentBtn = btn
        
        }
        
        addArrangedSubview(btn)
        
        return btn;
    }
    
    // MARK: - 给外界提供方法
    func setupCurrentButton(tag:Int){
        
        //获取btn
        let button = viewWithTag(tag + tagNumber) as! UIButton
        
        selectBtn(button)
        
    }

    // MARK: - 按钮点击事件
    func btnClick(button:UIButton) {
        
        selectBtn(button)
        
        //执行闭包 告诉外界点击了哪个按钮
        closure?(type:WBEmoticonBottomViewType(rawValue: button.tag - tagNumber)!)
        
    }
    
    // MARK: - 抽取公共选中btn的方法
    func selectBtn(button:UIButton) {
        
        //如果两个按钮一样 直接返回
        if button == currentBtn{
            
            return
        }
        
        //取消上一个按钮的选中状态
        currentBtn?.selected = false
        
        //当前按钮选中
        button.selected = true
        
        //记录当前按钮
        currentBtn = button
        
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
